// +----------------------------------------------------------------------
// | Manong.Cloud [ 领酷码农云 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020 http://www.manong.cloud All rights reserved.
// +----------------------------------------------------------------------
// | Author: 稻草人 <qinuoyun@qq.com>
// +----------------------------------------------------------------------
// | Member: 围棋 飘逸者 Loumt Silence24
// +----------------------------------------------------------------------

import crypto from 'crypto'
import jsonwebtoken from 'jsonwebtoken'
import uuid from 'uuid'


class LoginController extends BasicController {
  /**
   * 处理用户登陆
   * @return {[type]} [description]
   */
  async actionCode() {
    let code = uuid.v4();
    let userInfo = await this.modules("Account.AccountCode").insert({
      code: code
    });
    return {
      code: code
    }
  }

  async actionSynchro() {
    if (!$_POST['code']) {
      throw new Error("code不能为空");
    }
    let code = $_POST['code'];
    let codeInfo = await this.modules("Account.AccountCode").where({
      code: code
    }).first();
    if (codeInfo) {
      if (codeInfo.account_id && codeInfo.status === 2) {
        let userInfo = await this.modules("User").where({"id": codeInfo.account_id}).first();
        if (!userInfo.mobile || !userInfo.id_card) {
          throw new Error('请先绑定手机和身份证');
        }
        let accountInfo = await this.modules("Account").where({
          mobile: userInfo.mobile,
          id_card: userInfo.id_card
        }).first();
        if (accountInfo) {
          //删除对应密码字段
          delete accountInfo["password"];
          accountInfo['login_type'] = 1
          accountInfo['status'] = 3
          accountInfo["token"] = this.getToken(accountInfo);
          //返回用户数据
          return accountInfo;
        } else {
          throw new Error("用户不存在")
        }
      } else {
        return codeInfo
      }
    } else {
      return false
    }
  }

  /**
   * 调整授权
   * @returns {Promise<*|boolean>}
   */
  async actionAuthorize() {
    let code = $_POST['code'];
    let codeInfo = await this.modules("Account.AccountCode").where({
      code: code
    }).first();
    if (codeInfo) {
      return await this.modules("Account.AccountCode").where({
        code: code
      }).update({
        account_id: $_POST['account_id'],
        status: $_POST['status'],
      });
    } else {
      return false
    }
  }

  /**
   * 处理用户登陆
   * @return {[type]} [description]
   */
  async actionIndex() {
    let {mobile, app_id, password} = $_POST
    if (!mobile) {
      throw new Error("请输入手机号码")
    }
    if (!app_id) {
      throw new Error("请确认端")
    }
    if (!password) {
      throw new Error("请输入密码")
    }

    let userInfo = await this.modules("Account").where({"mobile": $_POST['mobile']}).first();
    if (userInfo) {
      //返回信息
      let password = this.getPassword($_POST['password']);
      console.log("打印密码", password)
      if (userInfo["password"] === password) {
        //删除对应密码字段
        delete userInfo["password"];
        userInfo['login_type'] = 1
        userInfo["token"] = this.getToken(userInfo);
        //返回用户数据
        return userInfo;
      } else {
        throw new Error('密码错误');
      }
    } else {
      throw new Error('用户不存在');
    }
  }


  /**
   * code换open_id
   * @return {[type]} [description]
   */
  async actionWeCode() {
    let data = $_POST;

    if (!data.code) {
      throw new Error("参数缺失")
    }


    let $Weapp = wechat.get_instance("weapp", {
      appid: global.APP_ID,
      appsecret: global.APP_SECRET
    });

    let result = await $Weapp.weappLogin(data.code);
    if (!result) {
      throw new Error('登录失败');
    }
    return result;
  }

  /**
   * 执行微信小程序登录
   * @return {[type]} [description]
   */
  async actionWeApp() {
    console.log("----新家 小程序登录----")
    let data = $_POST;

    if (!data.code && !data.open_id) {
      throw new Error("参数缺失")
    }

    if (data.code) {
      let $Weapp = wechat.get_instance("weapp", {
        appid: global.APP_ID,
        appsecret: global.APP_SECRET
      });

      let result = await $Weapp.weappLogin(data.code);
      if (!result) {
        throw new Error('登录失败');
      }

      data.open_id = result.openid
    }

    let {open_id} = data;

    let userData = await this.modules("User").where({open_id}).first();
    if (userData) {
      userData['login_type'] = 2
      userData["token"] = this.getToken(userData);
      return userData;
    } else {
      userData = await this.modules("User").validateCreate({open_id})
      userData['login_type'] = 2
      userData['open_id'] = open_id
      userData["token"] = this.getToken(userData);
      return userData;
    }
  }


  /**
   * 注册用户
   * @return {[type]} [description]
   */
  async actionRegister() {
    let userInfo = await this.modules("Account").where({"mobile": $_POST['mobile']}).first();
    if (userInfo && userInfo.mobile) {
      throw new Error('注册的手机号已经存在');
    } else {
      $_POST['password'] = this.getPassword($_POST['password']);
      return this.modules("Account").insert($_POST);
    }
  }

  /**
   * 执行微信小程序登录
   * @return {[type]} [description]
   */
  // async actionWeapp() {
  //   try {
  //     let $Weapp = wechat.get_instance("weapp", {
  //       appid: 'wxf59ceabb1f3faf35',
  //       appsecret: '1fef9720c260cb9b48a3cce297cceb1a'
  //     });
  //     let userInfo = $_POST['userInfo'];
  //     let result = await $Weapp.weappLogin($_POST['code']);
  //     //判断用户是否存在
  //     let userData = await this.modules("Account").where({"openid": result['openid']}).first();
  //     if (userData) {
  //       userData["token"] = this.getToken(userData);
  //       return userData;
  //     } else {
  //       let postData = Object.assign(userInfo, result);
  //       console.log("postData", postData)
  //       userData = await this.modules("Account").insert(postData);
  //       console.log("userData", userData)
  //       userData["token"] = this.getToken(userData);
  //       return userData;
  //     }
  //   } catch (error) {
  //     throw new Error('登录失败');
  //   }
  // }

  /**
   * 解析验证Token数据使用
   * @return {[type]} [description]
   */
  static findIdentityByAccessToken(token) {
    let self = new this();
    return new Promise((resolve, reject) => {
      try {
        let $data = jsonwebtoken.verify(token.slice(7), __SECRET__);

        console.log("Token中获取的信息")
        console.dir($data)

        let {login_type} = $data;
        if (!login_type) {
          reject("登录信息有误====")
        }


        if (login_type === 1) {
          P("管理员登录")
          /**
           * 管理员登录
           */
          self.modules("Account").where({id: $data['id']}).first().then(data => {
            resolve(data);
          }).catch(err => {
            reject(err);
          });

        }

        if (login_type === 2) {
          P("小程序登录")
          /**
           * 小程序登录
           */
          self.modules("User").where({open_id: $data['open_id']}).first().then(data => {
            resolve(data);
          }).catch(err => {
            reject(err);
          });
        }

      } catch (error) {
        // console.log(777,error)
        reject(error);
      }
    })
  }

  /**
   * 获取Token信息
   * @param  {[type]} USER [description]
   * @return {[type]}      [description]
   */
  getToken(USER) {
    return jsonwebtoken.sign({
      mobile: USER.mobile,
      id: USER.id,
      open_id: USER.open_id,
      login_type: USER.login_type,
      user_name: USER.user_name
    }, __SECRET__, {expiresIn: '12h'});
  }

  /**
   * 设置登陆密码
   * @param  {[type]} str [description]
   * @return {[type]}     [description]
   */
  getPassword(str) {
    let key = 'W4xOLXEvo*$8pk%aruoV!&t$5NAp0HHl';
    var obj = crypto.createHash('md5');
    obj.update(str + key);
    return obj.digest('hex');

  }
}

export default LoginController;
